using HealthCheck.Api.HealthChecks;
using HealthChecks.UI.Client;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using RabbitMQ.Client;

var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;

builder.Services
	.AddSingleton<IConnection>(_ =>
	{
		var factory = new ConnectionFactory
		{
			Uri = new Uri(configuration["RabbitMQ:Uri"]!)
		};
		return factory.CreateConnectionAsync().GetAwaiter().GetResult();
	})
	.AddHealthChecks()
	.AddCheck(
		"self", 
		() => HealthCheckResult.Healthy(),
		tags: ["self"])
	.AddSignalRHub(
		url:configuration["SignalR:Uri"]!,
		name: "signalR", 
		tags: ["im","signalr"])
	.AddRabbitMQ(
		name: "rabbitmq",
		tags: ["message-broker", "rabbitmq"]
	)
	.AddRedis(
		configuration.GetConnectionString("Redis")!,
		name: "redis",
		tags: ["distributed-cache","redis"])
	.AddNpgSql(
		configuration.GetConnectionString("Database")!,
		name: "database",
		tags: ["database", "postgresql"])
	.AddElasticsearch(
		elasticsearchUri: configuration["Elasticsearch:Url"]!,
		name: "elasticsearch",
		tags: ["search","elasticsearch"]
	)
	// 添加自定义健康检查
	.AddCheck<ExampleCustomHealthCheck>("example-custom-check", tags: ["custom"])
	.AddCheck<ExternalApiHealthCheck>("external-api-check", tags: ["external-api"])
	.AddCheck<DiskStorageHealthCheck>("disk-storage-check", tags: ["storage"]);

builder.Services.AddHealthChecksUI(options =>
{
    options.AddHealthCheckEndpoint("default", "/health");
    options.SetEvaluationTimeInSeconds(120); // 设置健康检查的频率
    options.SetMinimumSecondsBetweenFailureNotifications(60); // 设置失败通知的频率
    options.MaximumHistoryEntriesPerEndpoint(50); // 设置历史记录的条数
}).AddInMemoryStorage();

var app = builder.Build();
// 添加一个示例API端点
app.MapGet("/", () => Results.Ok(new { message = "API is working" }));
app.MapHealthChecks("health", new HealthCheckOptions
{
	
	Predicate = _ => true,
    ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});

app.MapHealthChecksUI(options => 
{
    options.UIPath = "/health-ui"; 
});

app.UseHttpsRedirection();
app.Run();
